<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:type:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="isSingleSelectDisabled"
          @click="handleUpdate"
          v-hasPermi="['system:type:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="isMultipleSelectDisabled"
          @click="handleDelete"
          v-hasPermi="['system:type:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:type:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getTypeList"></right-toolbar>
    </el-row>

    <el-table v-loading="isTableLoading" :data="roomTypeList" @selection-change="handleTableSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="房间图片" align="center" prop="roomImage" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.roomImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="房间类型" align="center" prop="roomType" />
      <el-table-column label="床位费用" align="center" prop="bedFee" />
      <!-- 表格创建人列：使用后端返回的creator字段匹配姓名 -->
      <el-table-column label="创建人" align="center" prop="creator">
        <template #default="scope">
          {{ getCreatorNameByCreator(scope.row.creator) }}
        </template>
      </el-table-column>
      <el-table-column label="房型介绍" align="center" prop="roomDescription" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.status === 1">启用</el-tag>
          <el-tag type="danger" v-else-if="scope.row.status === 0">禁用</el-tag>
          <span v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:type:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:type:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="totalCount>0"
      :total="totalCount"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getTypeList"
    />

    <!-- 添加或修改房型设置对话框 -->
    <el-dialog :title="dialogTitle" v-model="isDialogOpen" width="500px" append-to-body>
      <el-form ref="roomTypeFormRef" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="房间类型" prop="roomType">
          <el-input v-model="formData.roomType" placeholder="请输入房间类型" />
        </el-form-item>
        <el-form-item label="房间图片" prop="roomImage">
          <image-upload v-model="formData.roomImage"/>
        </el-form-item>
        <el-form-item label="床位费用" prop="bedFee">
          <el-input v-model="formData.bedFee" placeholder="请输入床位费用" />
        </el-form-item>
        <!-- 弹窗创建人下拉框：绑定formData.creator（存储数字ID） -->
        <el-form-item label="创建人" prop="creator">
          <el-select 
            v-model="formData.creator" 
            placeholder="请选择创建人" 
            clearable
            :loading="isCreatorLoading"
          >
            <el-option 
              v-for="item in creatorOptions" 
              :key="item.userId" 
              :label="item.nickName" 
              :value="item.userId" 
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房型介绍" prop="roomDescription">
          <el-input v-model="formData.roomDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancelForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RoomTypeManagement">
import { listType, getType, delType, addType, updateType } from "@/api/system/type"
// 导入用户查询接口（参考护理员查询代码）
import { listUser } from "@/api/system/user"
import { getCurrentInstance } from "vue"

const { proxy } = getCurrentInstance()

// 表格数据相关
const roomTypeList = ref([])
const isTableLoading = ref(true)
const totalCount = ref(0)
const selectedIds = ref([])
const isSingleSelectDisabled = ref(true)
const isMultipleSelectDisabled = ref(true)

// 弹窗相关
const isDialogOpen = ref(false)
const dialogTitle = ref("")

// 动态创建人选项
const creatorOptions = ref([])
const isCreatorLoading = ref(false)

// 表单相关数据（核心：使用creator字段匹配后端）
const data = reactive({
  formData: {
    id: null,
    roomImage: null,
    roomType: null,
    bedFee: null,
    creator: null, // 存储后端需要的数字ID（与后端creator字段对应）
    roomDescription: null,
    createTime: null,
    status: 1,
    isDeleted: null,
    extraField1: null,
    extraField2: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  formRules: {
    roomType: [
      { required: true, message: "房间类型不能为空", trigger: "change" }
    ],
    creator: [ // 校验creator字段，确保选择
      { required: true, message: "请选择创建人", trigger: "change" }
    ],
    status: [
      { required: true, message: "请选择状态", trigger: "change" }
    ]
  }
})

const { queryParams, formData, formRules } = toRefs(data)

/**
 * 加载创建人列表（参考护理员查询逻辑）
 */
const loadCreatorList = async () => {
  try {
    isCreatorLoading.value = true
    // 根据实际业务需求调整查询参数
    const res = await listUser({ 
      // 可以添加角色筛选，如：role: '管理员'
      // 或者状态筛选：status: 0
    })
    if (res.code === 200 && Array.isArray(res.rows)) {
      creatorOptions.value = res.rows
    } else {
      console.warn('未查询到创建人数据')
      creatorOptions.value = []
    }
  } catch (error) {
    console.error('加载创建人列表失败:', error)
    proxy?.$modal.msgError('加载创建人列表失败')
    creatorOptions.value = []
  } finally {
    isCreatorLoading.value = false
  }
}

/**
 * 根据后端creator字段（数字ID）匹配动态列表的姓名
 * @param {Number|String} creator - 后端返回的创建人ID（可能是数字或字符串）
 * @returns {String} 匹配的姓名或默认值
 */
function getCreatorNameByCreator(creator) {
  if (!creator) return "未知创建人"
  // 转为数字类型，确保与用户列表的userId（数字）匹配
  const creatorNum = Number(creator)
  const matchedItem = creatorOptions.value.find(
    item => item.userId === creatorNum
  )
  return matchedItem ? matchedItem.nickName : "未知创建人"
}

/** 查询房型列表 */
function getTypeList() {
  isTableLoading.value = true
  listType(queryParams.value).then(response => {
    roomTypeList.value = response.rows
    totalCount.value = response.total
    isTableLoading.value = false
  })
}

/** 取消表单 */
function cancelForm() {
  isDialogOpen.value = false
  resetForm()
}

/** 重置表单 */
function resetForm() {
  data.formData = {
    id: null,
    roomImage: null,
    roomType: null,
    bedFee: null,
    creator: null,
    roomDescription: null,
    createTime: null,
    status: 1,
    isDeleted: null,
    extraField1: null,
    extraField2: null
  }
  proxy?.resetForm("roomTypeFormRef")
}

/** 搜索操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getTypeList()
}

/** 重置查询 */
function resetQuery() {
  proxy?.resetForm("queryRef")
  handleQuery()
}

/** 表格选中变化 */
function handleTableSelectionChange(selection) {
  selectedIds.value = selection.map(item => item.id)
  isSingleSelectDisabled.value = selection.length !== 1
  isMultipleSelectDisabled.value = selection.length === 0
}

/** 新增操作 */
function handleAdd() {
  resetForm()
  isDialogOpen.value = true
  dialogTitle.value = "添加房型设置"
}

/** 修改操作：确保creator为数字类型 */
function handleUpdate(row) {
  resetForm()
  const targetId = row?.id || selectedIds.value
  getType(targetId).then(response => {
    formData.value = response.data
    // 转为数字，避免后端返回字符串导致下拉框不匹配
    formData.value.creator = Number(formData.value.creator)
    formData.value.status = Number(formData.value.status)
    isDialogOpen.value = true
    dialogTitle.value = "修改房型设置"
  })
}

/** 提交表单：确保存储数字ID */
function submitForm() {
  proxy.$refs["roomTypeFormRef"].validate(valid => {
    if (valid) {
      // 最终提交前转为数字，与后端字段类型一致
      formData.value.creator = Number(formData.value.creator)
      formData.value.status = Number(formData.value.status)

      const requestFn = formData.value.id ? updateType : addType
      requestFn(formData.value).then(() => {
        proxy.$modal.msgSuccess(formData.value.id ? "修改成功" : "新增成功")
        isDialogOpen.value = false
        getTypeList()
      })
    }
  })
}

/** 删除操作 */
function handleDelete(row) {
  const targetIds = row?.id || selectedIds.value
  proxy.$modal.confirm(`是否确认删除房型设置编号为"${targetIds}"的数据项？`).then(() => {
    return delType(targetIds)
  }).then(() => {
    getTypeList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出操作 */
function handleExport() {
  proxy.download('system/type/export', {
    ...queryParams.value
  }, `room_type_${new Date().getTime()}.xlsx`)
}

// 初始化加载列表和创建人数据
onMounted(async () => {
  try {
    // 并行加载房型列表和创建人数据
    await Promise.all([
      getTypeList(),
      loadCreatorList()
    ])
  } catch (error) {
    console.error('页面初始化失败:', error)
    proxy?.$modal.msgError('页面初始化失败')
  }
})
</script>